package com.xuyiwei.mayi.test;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;
import org.xml.sax.XMLReader;

import java.io.File;
import java.util.Iterator;
import java.util.List;

/**
 * Created by xuyiwei on 2019/4/13.
 */
public class Xmltest1 {
    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("/Users/xuyiwei/Downloads/mayitest/springioc/src/main/java/com/xuyiwei/mayi/test/student.xml"));
        Element element = document.getRootElement();
        getNodes(element);
    }

    private static void getNodes(Element element) {
        String text = element.getTextTrim();
        if(!StringUtils.isEmpty(text)){
            System.out.println("当前节点名称:"+element.getName()+"----"+element.getTextTrim());
        }

        List<Attribute> list = element.attributes();
        for(Attribute attr :list){
            System.out.println("当前节点属性:"+attr.getName()+":"+attr.getValue());
        }

        // 使用迭代器遍历
        Iterator<Element> elementIterator = element.elementIterator();
        while (elementIterator.hasNext()) {
            Element next = elementIterator.next();
            getNodes(next);
        }

    }
}
